﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Model.WXshopBuiness;
using Model.WXshopBuiness.DTO;
using Xproject.Framework.Core.Repositories;
using Xproject.Framework.Utility.Extensions;


namespace Repository.WXshopBuiness
{
    public  static class OrderRep
    {
        public static WeiXinOrder Get(this IRepositoryAsync<WeiXinOrder> repository, string orderId)
        {
            Expression<Func<WeiXinOrder, bool>> express = i => 1 == 1;
            if (!string.IsNullOrEmpty(orderId))
            {
                express = express.AndAlso(i => i.OrderID.Contains(orderId));
            }
            else
            {
                return null;
            }
            return repository.Query().Where(express).Select().FirstOrDefault();             
        }

        public static List<WeiXinOrder> GetUserAllOrderList(this IRepositoryAsync<WeiXinOrder> repository, string userId)
        {
            Expression<Func<WeiXinOrder, bool>> express = i => i.IsDel == 0;                       
            express = express.AndAlso(i => i.UserID == userId);           
            return repository.Query().Where(express).Select().OrderByDescending(i=>i.CreateTime).ThenBy(i=>i.OrderState).ToList();
        }


        public static List<OrderInfoModel> AdminGetUserOrderDetailList(this IRepositoryAsync<WeiXinOrder> repository, int offset, int limit, string orderCode,
            string userCode, string mobile, int? orderState, int? orderSource,int? payType,
            DateTime? startTime, DateTime? endTime, string order, string ordername)
        {
            string whereCondit = string.Format(@" where  1=1 ");
            if (!string.IsNullOrEmpty(orderCode))
            {
                whereCondit += string.Format(@" and o.OrderCode like '%{0}%' ",orderCode);
            }
            if (!string.IsNullOrEmpty(userCode))
            {
                whereCondit += string.Format(@" and u.UserCode like '%{0}%' ", userCode);
            }
            if (!string.IsNullOrEmpty(mobile))
            {
                whereCondit += string.Format(@" and o.Mobile like '%{0}%' ", mobile);
            }
            if (orderState.HasValue)
            {
                whereCondit += string.Format(@" and o.OrderState ={0} ", orderState.Value);
            }
            if (orderSource.HasValue)
            {
                whereCondit += string.Format(@" and o.OrderSource ={0} ", orderSource.Value);
            }
            if (payType.HasValue)
            {
                whereCondit += string.Format(@" and o.PayType ={0} ", payType.Value);
            }
            string exeTotalSql = string.Format(@"
              declare   @TOTAL INT
              SELECT  @TOTAL =count(o.[OrderID] )  
              FROM [WeiXin_Order] o inner join WeiXin_Product p
              on p.ProductID = o.ProductId
              inner join WeiXin_User u 
              on o.UserID = u.UserID            
                {0}

            ",whereCondit);

            string exeSql = string.Format(@"
        select * from ( 
              SELECT ROW_NUMBER() OVER(order by o.CreateTime desc) AS RowId,  o.[OrderID],o.[UserID],o.[OrderCode],o.[CreateTime],o.[OrderMoney],o.[OrderSource],o.[OrderName]
                  ,o.[PayType],o.[AddressID],o.[OrderState],o.[Remark],o.[ConfirmTime],o.[ConfirmPayState]
                  ,o.[SendGoodsTime],o.[SendGoodsName],o.[SignTime],o.[UserName],o.[Mobile]
                  ,o.[AreaCode],o.[Area],o.[Detail],o.[KDName],o.[KDCode],o.[KDMoney]
                  ,o.[UseScore],o.[UseCash],o.[UseBalance],o.[UseCoupon]
                  ,o.[OrderType],o.[OrderGift],o.[CheckTime],o.[CheckResult],o.[OrderCommissionMoney],o.[Province],o.[City],o.IsDel
                  ,o.ProductNum,o.ShopCarId,o.ThatTimeSalePrice
                  ,o.[IsSettlement],o.[Platform],o.[ProductId],P.ProductName,P.ThumbnailUrl1 AS ProductImg,P.ShortDesc,P.Domain as Domain
	              ,P.MarketPrice,P.CostPrice,P.SalePrice,P.Stock,o.PromotionID
	              ,u.NickName,u.UserCode,u.HeadUrl,a.Area+a.DetailAddress as DetailAddress,a.Phone,a.Receiver 
                  ,@TOTAL AS Total
              FROM [WeiXin_Order] o inner join WeiXin_Product p
              on p.ProductID = o.ProductId
              inner join WeiXin_User u 
              on o.UserID = u.UserID
              left join [Address] a on a.AddressID =o.AddressID
                {0}
            )  as b
         where RowId between {1} and {2} 
            ", whereCondit, offset, offset+limit);
            return repository.SqlQueryT<OrderInfoModel>(exeTotalSql+exeSql).ToList();
        }


        public static OrderInfoModel GetOrderInfoByOrderId(this IRepositoryAsync<WeiXinOrder> repository, string orderId)
        {
            string orderIdCondit = string.Format(" and o.OrderID='{0}' ", orderId);
         
            string exeSql = string.Format(@"  
                SELECT  o.[OrderID],o.[UserID],o.[OrderCode],o.[CreateTime],o.[OrderMoney],o.[OrderSource],o.[OrderName]
      ,o.[PayType],o.[AddressID],o.[OrderState],o.[Remark],o.[ConfirmTime],o.[ConfirmPayState]
      ,o.[SendGoodsTime],o.[SendGoodsName],o.[SignTime],o.[UserName],o.[Mobile]
      ,o.[AreaCode],o.[Area],o.[Detail],o.[KDName],o.[KDCode],o.[KDMoney]
      ,o.[UseScore],o.[UseCash],o.[UseBalance],o.[UseCoupon]
      ,o.[OrderType],o.[OrderGift],o.[CheckTime],o.[CheckResult],o.[OrderCommissionMoney],o.[Province],o.[City],o.IsDel
      ,o.ProductNum,o.ShopCarId,ps.ProductSpecificationId,ps.SalesPrice as SpeciSalesPrice,ps.OrignPrice as SpeciOrignPrice,O.NeedToPay,o.ThatTimeSalePrice
      ,o.[IsSettlement],o.[Platform],o.[ProductId],P.ProductName,P.ThumbnailUrl1 AS ProductImg,P.ShortDesc,P.Domain as Domain
	  ,P.MarketPrice,P.CostPrice,P.SalePrice,P.Stock,p.Spec1,p.Spec2,p.Spec3,p.Spec4,p.Spec5,UPKJ.KanJiaID,UPKJ.AleradKanJiaMoney
	  ,a.Area + a.DetailAddress as DetailAddress,a.AddressID,a.Phone as receivePhone,a.Receiver  ,a.IsDefault,a.Tag,o.PromotionID
      FROM [WeiXin_Order] o inner join WeiXin_Product p
      on p.ProductID = o.ProductId
      inner join ShoppingCar sc
      on sc.ShopCarId = o.ShopCarId
      left join ProductSpecification ps 
      on ps.ProductSpecificationId = sc.ProductSpecificationId
      left join [Address] A
      on A.AddressID = o.AddressID
    left join User_Product_KanJia UPKJ
      on o.OrderID = UPKJ.OrderId
              where o.IsDel=0  {0}    
order by o.CreateTime desc,o.OrderState 
                            ", orderIdCondit);
            return repository.SqlQueryT<OrderInfoModel>(exeSql).FirstOrDefault();
        }

        public static List<OrderInfoModel> GetUserAllOrderDetailList(this IRepositoryAsync<WeiXinOrder> repository, string userId)
        {
            string userIdCondit = string.Format(" and o.OrderState>0  and o.UserID='{0}'  ", userId);
            string exeSql = string.Format(@"  
               SELECT  o.[OrderID],o.[UserID],o.[OrderCode],o.[CreateTime],o.[OrderMoney],o.[OrderSource],o.[OrderName]
      ,o.[PayType],o.[AddressID],o.[OrderState],o.[Remark],o.[ConfirmTime],o.[ConfirmPayState]
      ,o.[SendGoodsTime],o.[SendGoodsName],o.[SignTime],o.[UserName],o.[Mobile]
      ,o.[AreaCode],o.[Area],o.[Detail],o.[KDName],o.[KDCode],o.[KDMoney]
      ,o.[UseScore],o.[UseCash],o.[UseBalance],o.[UseCoupon]
      ,o.[OrderType],o.[OrderGift],o.[CheckTime],o.[CheckResult],o.[OrderCommissionMoney],o.[Province],o.[City]
      ,o.ProductNum,o.ShopCarId,ps.ProductSpecificationId,ps.SalesPrice as SpeciSalesPrice,ps.OrignPrice as SpeciOrignPrice,O.NeedToPay,o.ThatTimeSalePrice
      ,o.[IsSettlement],o.[Platform],o.[ProductId],P.ProductName,P.ThumbnailUrl1 AS ProductImg,P.ShortDesc,P.Domain as Domain
	  ,P.MarketPrice,P.CostPrice,P.SalePrice,P.Stock,p.Spec1,p.Spec2,p.Spec3,p.Spec4,p.Spec5,UPKJ.KanJiaID,UPKJ.AleradKanJiaMoney,o.PromotionID 
  FROM [WeiXin_Order] o inner join WeiXin_Product p
  on p.ProductID = o.ProductId
      inner join ShoppingCar sc
      on sc.ShopCarId = o.ShopCarId
      left join ProductSpecification ps 
      on ps.ProductSpecificationId = sc.ProductSpecificationId
left join User_Product_KanJia UPKJ
  on o.OrderID = UPKJ.OrderId
              where o.IsDel=0  {0}  
order by o.CreateTime desc,o.OrderState 
                            ", userIdCondit);
            return repository.SqlQueryT<OrderInfoModel>(exeSql).ToList();
        }


        public static List<OrderInfoModel> GetUserAllOrderDetailList(this IRepositoryAsync<WeiXinOrder> repository, string userId, int orderState)
        {
            string userIdCondit = string.Format(" and o.UserID='{0}' ", userId);
            string stateCondit = string.Format(" and o.OrderState={0} ",orderState);
            string exeSql = string.Format(@"  
               SELECT  o.[OrderID],o.[UserID],o.[OrderCode],o.[CreateTime],o.[OrderMoney],o.[OrderSource],o.[OrderName]
      ,o.[PayType],o.[AddressID],o.[OrderState],o.[Remark],o.[ConfirmTime],o.[ConfirmPayState]
      ,o.[SendGoodsTime],o.[SendGoodsName],o.[SignTime],o.[UserName],o.[Mobile]
      ,o.[AreaCode],o.[Area],o.[Detail],o.[KDName],o.[KDCode],o.[KDMoney]
      ,o.[UseScore],o.[UseCash],o.[UseBalance],o.[UseCoupon]
      ,o.[OrderType],o.[OrderGift],o.[CheckTime],o.[CheckResult],o.[OrderCommissionMoney],o.[Province],o.[City]
      ,o.ProductNum,o.ShopCarId,ps.ProductSpecificationId,ps.SalesPrice as SpeciSalesPrice,ps.OrignPrice as SpeciOrignPrice,O.NeedToPay,o.ThatTimeSalePrice
      ,o.[IsSettlement],o.[Platform],o.[ProductId],P.ProductName,P.ThumbnailUrl1 AS ProductImg,P.ShortDesc,P.Domain as Domain
	  ,P.MarketPrice,P.CostPrice,P.SalePrice,P.Stock,p.Spec1,p.Spec2,p.Spec3,p.Spec4,p.Spec5,UPKJ.KanJiaID,UPKJ.AleradKanJiaMoney,o.PromotionID
  FROM [WeiXin_Order] o inner join WeiXin_Product p
   on p.ProductID = o.ProductId
      inner join ShoppingCar sc
      on sc.ShopCarId = o.ShopCarId
      left join ProductSpecification ps 
      on ps.ProductSpecificationId = sc.ProductSpecificationId
left join User_Product_KanJia UPKJ
  on o.OrderID = UPKJ.OrderId
              where o.IsDel=0  {0} {1}  
order by o.CreateTime desc,o.OrderState 
                            ", userIdCondit, stateCondit);
            return repository.SqlQueryT<OrderInfoModel>(exeSql).ToList();
        }

        /// <summary>
        /// 得到带状态的用户的   订单
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="userId"></param>
        /// <param name="orderState"></param>
        /// <returns></returns>
        public static List<WeiXinOrder> GetUserOrderList(this IRepositoryAsync<WeiXinOrder> repository, string userId, int orderState)
        {
            Expression<Func<WeiXinOrder, bool>> express = i => i.IsDel == 0;
            if (!string.IsNullOrEmpty(userId))
            {
                express = express.AndAlso(i => i.UserID == userId);
            }
            express = express.AndAlso(i => i.OrderState == orderState);
            return repository.Query().Where(express).Select().ToList();
        }
    }
}
